package top.atluofu.luofuecommerce.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import top.atluofu.common.utils.HttpUtils;
import top.atluofu.common.utils.R;
import top.atluofu.luofuecommerce.authserver.feign.MemberFeignService;
import top.atluofu.luofuecommerce.authserver.vo.MemberRespVo;
import top.atluofu.luofuecommerce.authserver.vo.SocialUser;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: OAuth2Controller
 * @description: TODO
 * @author: 有罗敷的马同学
 * @datetime: 2022Year-11Month-24Day-14:46
 * @Version: 1.0
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登陆回调
     *
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();

        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", "1643498253");
        map.put("client_secret", "71010dc8034f9073abe422d89337087e");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.atluofu.top/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);

        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            R oauth2Login = memberFeignService.oauth2Login(socialUser);
            if (oauth2Login.getCode() == 0) {
                MemberRespVo data = oauth2Login.getData("data", new TypeReference<MemberRespVo>() {
                });
                session.setAttribute("loginUser", data);
                log.info("登录成功：用户:{}", data.toString());
                return "redirect:http://atluofu.top";
            } else {
                return "redirect:http://auth.atluofu.top/login.html";
            }
        } else {
            return "redirect:http://auth.atluofu.top/login.html";
        }
    }
}
